//
//  DDDDforgetPassWordViewController.m
//  DingDongZP
//
//  Created by 靜 on 16/6/3.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDDDforgetPassWordViewController.h"
#import "DDGetVerifyCodeService.h"
#import <AFNetworking/AFNetworking.h>
#import "DDLoginViewController.h"

@interface DDDDforgetPassWordViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *passWordTextField;
@property (weak, nonatomic) IBOutlet UITextField *yanZhengMaTextField;
@property (weak, nonatomic) IBOutlet UIButton *getCodeButton;
@property (nonatomic) int countDownTime;
@property (nonatomic) NSTimer *timer;
@property (strong, nonatomic) DDGetVerifyCodeService *getVerifyCodeService;
@property (weak, nonatomic) IBOutlet UIButton *yanZhengmaButtonClick;


@end

@implementation DDDDforgetPassWordViewController
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.getVerifyCodeService = [[DDGetVerifyCodeService alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setRegisterNavgationBar];
    
    self.countDownTime = 60;
}
- (void)setRegisterNavgationBar
{
    self.navigationController.navigationBar.translucent = NO;
    
    if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
        NSArray *list = self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView = (UIImageView *)obj;
                NSArray *list2 = imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2 = (UIImageView *)obj2;
                        imageView2.hidden = YES;
                    }
                }
            }
        }
    }
}

- (IBAction)yanZhengmaButtonClick:(id)sender {
    
    if (![self validatePhoneNumber:self.phoneTextField.text]) {
        [self showText:@"手机号码格式有误"];
        return;
    }
    [self showLoading];
    WEAKSELF
    [self.getVerifyCodeService queryRegisterWithMobile:_phoneTextField.text successBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([weakSelf isValidateResponseData:responseObject]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf showText:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                
                NSLog(@"%@",responseObject);
                
            });
            
            //获取成功后 倒计时
            weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:weakSelf selector:@selector(countDown) userInfo:nil repeats:YES];
            weakSelf.countDownTime = 60;
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf showText:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
            });
        }
        
    } failBlock:^(id responseObject, NSError *error) {
        [weakSelf requestFaild];
    }];

    
}


- (BOOL)validatePhoneNumber:(NSString *)string
{
    if (string.length != 11) {
        return NO;
    }
    return YES;
}

- (BOOL)validatePassword:(NSString *)password
{
    if (password.length < 6 || password.length > 25) {
        return NO;
    }
    return YES;
}

- (IBAction)zhongZhiMiMaButtonClick:(id)sender {
    
    if (![self validatePhoneNumber:self.phoneTextField.text]) {
        [self showText:@"手机号码格式有误"];
        return;
    }
    if (![self validatePassword:self.passWordTextField.text]) {
        [self showText:@"密码格式有误"];
        return;
    }
    if (self.yanZhengMaTextField.text.length < 1) {
        [self showText:@"验证码格式有误"];
        return;
    }
    [self showLoading];

    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:_phoneTextField.text,@"mobile",_passWordTextField.text,@"password",_yanZhengMaTextField.text,@"code", nil];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",@"text/json",@"text/plain",@"text/html", nil];
    NSString *url = [NSString stringWithFormat:@"http://114.55.59.142/appws/resetpassword.php"];
    
    [manager POST:url parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    }  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"%@",[responseObject objectForKey:@"msg"] );
        if ([[responseObject objectForKey:@"code"] isEqualToString:@"成功"] ) {
            DDLoginViewController *vc = [[DDLoginViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"______%@",error);
        
    }];

    

    
}

- (void)countDown
{
    self.countDownTime --;
    if (self.countDownTime == 0)
    {
        if ([self.timer isValid]) {
            
            [self.timer invalidate];
            [self changeButtonState];
            return;
        }
    }
    
    [self.getCodeButton setTitle:[NSString stringWithFormat:@"已发送(%d)",self.countDownTime] forState:UIControlStateNormal];
    [self.getCodeButton setUserInteractionEnabled:NO];
}
- (void)changeButtonState
{
    [self.getCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.getCodeButton setUserInteractionEnabled:YES];
}

- (void)stopTimer {
    if (nil != self.timer && [self.timer isValid]) {
        [self.timer invalidate];
        self.timer = nil;
    }
}
#pragma mark
#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (self.view.bounds.origin.y > 190) {
        return;
    }
    CGRect newbounds = self.view.bounds;
    newbounds.origin.y +=190;
    
    [UIView animateWithDuration:.3f animations:^{
        self.view.bounds = newbounds;
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (self.view.bounds.origin.y == 190) {
        CGRect newbounds = self.view.bounds;
        newbounds.origin.y = 0;
        
        [UIView animateWithDuration:.3f animations:^{
            self.view.bounds = newbounds;
        }];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
